import NProgress from 'nprogress' // 网页顶部进度
import 'nprogress/nprogress.css' // 进度条样式
NProgress.configure({ showSpinner: false }) // 隐藏旋转图标

import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store'
import routes from './constantsRoutes'
import './routerHack'

Vue.use(Router)

const router = new Router({
  scrollBehavior: () => ({ y: 0 }),
  routes,
})

router.beforeEach(async (to, from, next) => {
  NProgress.start() // 进度条开始
  document.title = to.meta.title || to.name || process.env.VUE_APP_HOME_TITLE
  const { token } = store.state.user.user
  // 已经登录
  if (token) {
    // 动态设置加入路由
    const { generated } = store.state.menus
    if (!generated) {
      const routes = await store.dispatch('generateRoutes')
      router.addRoutes(routes)
      const { path = '/', query = {}, params = {} } = to
      next({ path, query, params })
    } else {
      // 已登录并且在登录页面
      next(to.path === '/login' ? { path: '/' } : undefined)
    }
  } else {
    // 没有登录
    next(to.path !== '/login' ? { path: '/login' } : undefined)
  }

  NProgress.done() // 进度条结束
})

router.afterEach(() => {
  NProgress.done() // 进度条结束
})
export default router
